package com.yonyou.brigade.third_parties.huazhu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.order_center.service.IBriOrderService;
import com.yonyou.brigade.third_parties.huazhu.constant.HZConstant;
import com.yonyou.brigade.third_parties.huazhu.service.IHzOrderService;
import com.yonyou.brigade.third_parties.huazhu.service.IHzPublicService;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.util.operateutil.AESUtil4ECB;
import com.yonyou.brigade.util.operateutil.JsonUtils;
import com.yonyou.brigade.ybz.service.IConvertService;
import com.yonyou.ybzboot.starter.common.util.StringUtil;
import com.yonyou.ybzboot.starter.mongodb.dao.IMongoDao;
import com.yonyou.ybzboot.starter.mongodb.model.CriteriaMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class HzOrderServiceImpl implements IHzOrderService {

    private static Logger logger = LoggerFactory.getLogger(HzOrderServiceImpl.class);


    @Autowired
    private IHzPublicService hzPublicService;

    @Value("${huazhu.baseUrl}")
    private String baseUrl;

    @Value("${huazhu.password}")
    private String password;

    @Autowired
    private IMongoDao mongoDao;

    @Autowired
    private IBriOrderService briOrderService;

    @Value("${huazhu.tradeType}")
    private String hzTradeType;

    @Value("${cnv.baigade.system.code}")
    private String systemCode;

    @Value("${cnv.register.userId}")
    private String cnvRegisterUserId;

    @Value("${cnv.register.tenant}")
    private String cnvRegisterTenant;

    @Value("${cnv.register.cookie}")
    private String cnvRegisterCookie;

    @Autowired
    private IConvertService convertService;

    @Override
    public void getOrders(String tenant, String orgPk, String beginDate, String endDate, BriChannel briChannel) {
        JSONObject config = JSONObject.parseObject(briChannel.getConfig());
        String configUrl = config.getString("baseUrl");
        String vCard = config.getString("vCard");
        String token = hzPublicService.getToken();
        if (StringUtil.isNotEmpty(config.getString("password"))){
            token = hzPublicService.getToken(config.getString("password"));
        }
        String url = baseUrl;
        if (StringUtil.isNotEmpty(configUrl)){
            url = configUrl;
        }
        url = url + HZConstant.GET_ORDER_URL_PATH;

        for (int i = 0; i < HZConstant.ORDER_STATUS.length; i++) {
            JSONObject reqParam = new JSONObject();
            reqParam.put("VCard", vCard);
            reqParam.put("QueryStartDate", beginDate);
            reqParam.put("QueryEndDate", endDate);
            reqParam.put("OrderStatus", HZConstant.ORDER_STATUS[i]);
            reqParam.put("Token", token);
            pullOrders(url, reqParam, tenant, briChannel);
        }
    }

    void pullOrders(String url, JSONObject reqParam, String tenant, BriChannel briChannel){
        logger.info("华住酒店拉取订单参数：" + reqParam.toJSONString());
        String strResult = HttpClientUtil.doPostJson(url, reqParam.toJSONString());
        logger.info("华住酒店拉取订单结果：" + strResult);

        if (!StringUtil.isEmpty(strResult) && JsonUtils.isJSONObject(strResult)) {
            JSONObject resultJSON = JSONObject.parseObject(strResult);
            if ("1".equals(resultJSON.getString("ResCode"))){
                JSONArray itemArr = resultJSON.getJSONArray("Items");
                if (CollectionUtils.isEmpty(itemArr)) {
                    logger.error("拉取华住酒店订单失败，Items为空");
                    return;
                }
                String psd = JSONObject.parseObject(briChannel.getConfig()).getString("password");
                for (int i = 0; i < itemArr.size(); i++) {
                    JSONObject item = itemArr.getJSONObject(i);
                    convertAndSave(item, tenant, briChannel.getId(), psd);
                }

            } else {
                logger.error("拉取华住酒店订单失败");
            }

        }
    }

    private void convertAndSave(JSONObject item, String tenant, Integer channelId, String psd) {
        if (StringUtil.isNotEmpty(psd)){
            decodeData(item, psd);
        }else {
            decodeData(item);
        }
        String uniqueId = item.getString("UniqueId");
        String orderNo = item.getString("OrderNo");
        dealWithMongo(orderNo, HZConstant.HOTEL_MONGO_ORDER_TABLENAME, item);

        logger.info("华住订单转换数据，"+ hzTradeType +"，"+ systemCode + "，" +  cnvRegisterUserId + "，" +  cnvRegisterTenant + "，" +  cnvRegisterCookie + ">>" + JSONObject.toJSONString(item));
        JSONObject res = convertService.convert(hzTradeType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, item);
        logger.info("华住订单转换结果："+ res);
        if (res.getBoolean("success")){
            JSONArray results = res.getJSONArray("result");
            if (results != null && results.size() > 0){
                for (int j = 0; j < results.size(); j++) {
                    JSONObject jsonObject = results.getJSONObject(j);
                    JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                    logger.info("存储华住酒店订单");
                    try {
                        briOrderService.saveHotel(orderCenter, orderNo, tenant, uniqueId, "huazhu", channelId);
                    }catch (Exception e){
                        e.printStackTrace();
                        logger.error("华住酒店订单存入订单中心时，设置离店日期时出现错误");
                    }
                }
            }
        }




    }

    private void decodeData(JSONObject item) {
        decodeData(item, password);
    }
    private void decodeData(JSONObject item, String psd) {
        String uniqueId = item.getString("UniqueId");
        uniqueId = AESUtil4ECB.decryptUtf8(uniqueId, psd);
        item.put("UniqueId", uniqueId);
        String applyNo = item.getString("ApplyNo");
        applyNo = AESUtil4ECB.decryptUtf8(applyNo, psd);
        item.put("ApplyNo", applyNo);
        JSONArray userInfoArr = item.getJSONArray("UserInfos");
        if (userInfoArr != null && userInfoArr.size() > 0){
            for (int i = 0; i < userInfoArr.size(); i++) {
                JSONObject userInfo = userInfoArr.getJSONObject(i);

                String cusName = userInfo.getString("CusName");
                cusName = AESUtil4ECB.decryptUtf8(cusName, psd);
                item.put("CusName", cusName);

                String idTypeID = userInfo.getString("IDTypeID");
                idTypeID = AESUtil4ECB.decryptUtf8(idTypeID, psd);
                item.put("IDTypeID", idTypeID);

                String idNo = userInfo.getString("IDNo");
                idNo = AESUtil4ECB.decryptUtf8(idNo, psd);
                item.put("IDNo", idNo);
            }
        }
    }

    private void dealWithMongo(String orderId, String mongoName, JSONObject orderJson) {
        logger.info("mongo查询参数【" +orderId+ ", " + mongoName + "】");
        CriteriaMap criteriaMap = new CriteriaMap();
        criteriaMap.put("orderId",orderId);
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap, JSONObject.class, mongoName);
        if(ordersources != null && ordersources.size() > 0) {
            logger.info("订单更新存入mongo");
            mongoDao.deleteByMap(criteriaMap, mongoName);
            mongoDao.getMongoTemplate().save(orderJson, mongoName);
        }
        else {
            logger.info("订单存入mongo");
            mongoDao.getMongoTemplate().insert(orderJson, mongoName);
        }
    }
}
